package com.hc.server.user.service.impl;

import com.hc.server.common.constant.RedisKey;
import com.hc.server.common.utils.JwtUtils;
import com.hc.server.common.utils.RedisUtils;
import com.hc.server.user.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Created by wdj on 2024/10/18
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    //token过期时间
    private static final Integer TOKEN_EXPIRE_DAYS = 5;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(Long uid) {
        String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        String token = RedisUtils.getStr(key);
        if(StringUtils.isNotBlank(token)){
            return token;
        }
        // 获取用户token
        token = jwtUtils.createToken(uid);
        RedisUtils.set(key, token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    /**
     * 校验token是不是有效
     * @param token
     * @return
     */
    @Override
    public boolean verify(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if(Objects.isNull(uid)){
            return false;
        }
        String key = RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
        String realToken = RedisUtils.getStr(key);
        return Objects.equals(token, realToken); // 有可能token失效了，需要校验是不是和最新token一致
    }

    @Override
    public Long getValidUid(String token) {
        boolean verify = verify(token);
        return verify? jwtUtils.getUidOrNull(token) : null;
    }
}
